import {LOGOUT,LOGIN} from '../actions/user'

// 实现数据持久化
let userInfo = localStorage.getItem('userInfo')
try {
    userInfo = JSON.parse(userInfo) || {}
} catch (err) {
    userInfo = {}
}

const initState = {
    userInfo,
}

function reducer(state=initState,{type,payload}){
    let newState = {...state}
    switch(type){
        // {type:'login',payload:{...}}
        case LOGIN:
            newState.userInfo = payload
            localStorage.setItem('userInfo',JSON.stringify(payload))
            return newState;
        case LOGOUT:
            newState.userInfo = {}
            localStorage.removeItem('userInfo')
            return newState;
        default:
            return newState
    }
}

export default reducer